import random
import time
from DataRecorder import Recorder

import requests
import pandas as pd
import json
from read_excel_content import get_complete_sheet1
from loguru import logger

df_sheet = get_complete_sheet1(file_path=r'D:\Users\Desktop\计划单元名修改.xlsx')

seller_id = '682bee94968e880015c84ac6'

headers = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9",
    "content-type": "application/json",
    "origin": "https://ad.xiaohongshu.com",
    "priority": "u=1, i",
    "referer": f"https://ad.xiaohongshu.com/aurora/ad/manage/campaign?vSellerId={seller_id}",
    "sec-ch-ua": "\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36",
    "v-seller-id": seller_id,
    "x-b3-traceid": "49558db2044d9beb"
}
cookies = {
    "a1": "1960e2acef4ev020adbqbgxdcps88phbukzabnajf50000272280",
    "webId": "4b6833e542f84e76fbfb34e006eddce8",
    "gid": "yjK8dJ0fS47WyjK8dJ0SdTI0i4dh8J80fDADuVikCfSUM028YYUxDD888JWJJY88jy8DJjDy",
    "customerClientId": "279177063808841",
    "abRequestId": "4b6833e542f84e76fbfb34e006eddce8",
    "x-user-id-pgy.xiaohongshu.com": "6426a4f7f95410000178a9cf",
    "x-user-id-fankui-out.xiaohongshu.com": "616fdd2b85d0b300016960dc",
    "web_session": "040069b47b667a0c594b2b060b3a4b889cab1f",
    "access-token-chengfeng.xiaohongshu.com": "customer.ad_wind.AT-68c517515803536915932823guzkz5ijjxu4daik",
    "system.alias": "ads_partner",
    "customer-sso-sid": "68c5175172380775582374509ggxj5vjb8brbqkg",
    "x-user-id-partner.xiaohongshu.com": "616fdd2b85d0b300016960dc",
    "ads-partner-sid": "7fd44ff20a94488bb451d4afbb21e951",
    "access-token-partner.xiaohongshu.com": "customer.ads_partner.AT-68c517517238077467206041iuzrlfkz0qirz3iy",
    "access-token-ad.xiaohongshu.com": "customer.leona.AT-68c517517238120417316763finsfuamvnnap9ys",
    "websectiga": "984412fef754c018e472127b8effd174be8a5d51061c991aadd200c69a2801d6",
    "sec_poison_id": "5fbd36f4-aa18-4634-91de-6a3c0b06d307",
    "loadts": "1750295773460",
    "acw_tc": "0a00074d17502957866198201e2d6776d8596ac5b314553ab3402fd449086b",
    "xsecappid": "aurora-shell",
    "ares.beaker.session.id": "1750295787638035082114"
}

c_headers = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9",
    "content-type": "application/json",
    "origin": "https://ad.xiaohongshu.com",
    "priority": "u=1, i",
    "referer": f"https://ad.xiaohongshu.com/aurora/ad/manage/creativity?vSellerId={seller_id}",
    "sec-ch-ua": "\"Google Chrome\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
    "v-seller-id": seller_id,
    "x-b3-traceid": "e5a25cf74599653e"
}
c_cookies = {
    "a1": "1960e2acef4ev020adbqbgxdcps88phbukzabnajf50000272280",
    "webId": "4b6833e542f84e76fbfb34e006eddce8",
    "gid": "yjK8dJ0fS47WyjK8dJ0SdTI0i4dh8J80fDADuVikCfSUM028YYUxDD888JWJJY88jy8DJjDy",
    "customerClientId": "279177063808841",
    "abRequestId": "4b6833e542f84e76fbfb34e006eddce8",
    "web_session": "030037a0c46d4170a8a7797f8f204a4cdb8649",
    "x-user-id-pgy.xiaohongshu.com": "6426a4f7f95410000178a9cf",
    "access-token-chengfeng.xiaohongshu.com": "customer.ad_wind.AT-68c517503734257907183822u84izng6bm6zxrb7",
    "webBuild": "4.62.3",
    "system.alias": "ads_partner",
    "acw_tc": "0a0d0e0317476475705268777e6b92abeb87cafc4c2d2866cbc1c1683a424a",
    "customer-sso-sid": "68c517506094084738023050pryyeyoch5ebntpm",
    "x-user-id-partner.xiaohongshu.com": "616fdd2b85d0b300016960dc",
    "ads-partner-sid": "2a9d385a3d824fde91eb990b4a99d08a",
    "access-token-partner.xiaohongshu.com": "customer.ads_partner.AT-68c517506094084738465835tywat1l98togx8h0",
    "loadts": "1747648716510",
    "xsecappid": "aurora-shell",
    "websectiga": "f47eda31ec99545da40c2f731f0630efd2b0959e1dd10d5fedac3dce0bd1e04d",
    "sec_poison_id": "44812e06-cd21-4ccb-9c11-b3be39ed6977",
    "ares.beaker.session.id": "1747648975213097297431",
    "access-token-ad.xiaohongshu.com": "customer.leona.AT-68c517506095192839589888dichxyf9zhrvgbfq"
}

# 接口基础 URL
base_url = "https://ad.xiaohongshu.com/api/leona/rtb"
r = Recorder(path='重复计划.csv', cache_size=500)
# 遍历每一行数据并发送请求
for index, row in enumerate(df_sheet.itertuples()):
    try:
        error_data = {}
        num = index+1
        logger.info(f"正在执行第{num}条")
        # 获取数据
        campaign_id = getattr(row, '计划ID', None)
        new_campaign_name = getattr(row, '修改计划名', None)
        unit_id = getattr(row, '单元ID', None)
        new_unit_name = getattr(row, '修改单元名', None)
        creative_id = getattr(row, '创意ID', None)
        new_creative_name = getattr(row, '修改创意名', None)

        # 修改计划名称
        if campaign_id and new_campaign_name:
            url = f"{base_url}/campaign"
            data = {
                "sourceFlag": "web",
                "campaignId": int(campaign_id),
                "campaignName": str(new_campaign_name)
            }
            response = requests.put(url, headers=headers, cookies=cookies, data=json.dumps(data, separators=(',', ':')))
            logger.info(f"第{num}条 - 计划ID: {campaign_id} 修改结果: {response.status_code}, {response.text}")

            plan_json = response.json()
            if plan_json['code'] != 0:
                r.add_data({'计划ID': campaign_id, '重复计划名': new_campaign_name})

        # 修改单元名称
        if unit_id and new_unit_name:
            url = f"{base_url}/unit/name"
            data = {
                "unitId": int(unit_id),
                "unitName": str(new_unit_name)
            }
            response = requests.put(url, headers=headers, cookies=cookies, data=json.dumps(data, separators=(',', ':')))
            logger.info(f"第{num}条 - 单元ID: {unit_id} 修改结果: {response.status_code}, {response.text}")
            unit_json = response.json()
            if unit_json['code'] != 0:
                r.add_data({'单元ID': unit_id, '重复单元名': new_unit_name})

        # 修改创意名称
        # if creative_id and new_creative_name:
        #     url = f"{base_url}/creativity/batch/update/name"
        #     data = {
        #         "creativityId": int(creative_id),
        #         "creativityName": str(new_creative_name)
        #     }
        #     response = requests.post(url, headers=c_headers, cookies=c_cookies, data=json.dumps(data, separators=(',', ':')))
        #     logger.info(f"第{num}条 - 创意ID: {creative_id} 修改结果: {response.status_code}, {response.text}")

        time.sleep(random.randint(1, 3))

    except Exception as e:
        logger.error(f"执行第{num}条时, 处理失败: {e}")

r.record()